window.SERVICE_URL = "https://app.quleyuan.com.cn/" ; 
window.WX_SERVICE_URL = "https://www.quleyuan.com.cn/" ; 
window.HOMEPAGE_URL = "http://homepage.quleyuan.com.cn/" ; 



var IOS_VERSION = 5 ; 
var ANDROID_VERSION = 5 ; 

var IOS_VERSION_CODE = '1.0.4' ; 
var ANDROID_VERSION_CODE  = '1.0.4' ;

var TALKINGDATA = null ; 

//ajax  load 页面

var reload_html = ''; 
    reload_html+='<div id="id_reload_div" class="list_poorNetwork_page">';
    reload_html+='<span></span>';
    reload_html+='<p class="p1">网络请求失败</p >';
    reload_html+='<p class="p2">请检查您的网络</p >';
    reload_html+='<button onclick="reloadPage()">重新加载</button>';
    reload_html+='</div>';
    
 





function loadPage(url_path,div_id  , js_id ){
    div_id =  !!div_id ? div_id : 'main_div' ;
    js_id = !!js_id ? js_id : 'main_script' ;  
    ReloadPageParam.url_path = url_path ;
    ReloadPageParam.div_id = div_id ;
    ReloadPageParam.js_id = js_id ; 
    api.ajax({
        url: SERVICE_URL+url_path+'?tempvar='+Math.random(),
        method: 'get',
        dataType:'text'
     },
    function(ret, err){
        if(ret) {    //有数据
            // 将 load到的 html  代码  替换掉  指定div 中的 内容
            $api.html($api.byId(div_id),ret);
            $api.css($api.byId(div_id),"background:none;");
            //执行相关 js 代码
            eval($api.html($api.byId(js_id)));  
        } else {   //错误 
            $api.html($api.byId(div_id),reload_html);
        }
    });
}

var ReloadPageParam = {} ; 

window.reloadPage = function(){
    // loadPage(ReloadPageParam.url_path,ReloadPageParam.div_id,ReloadPageParam.js_id);
    var jsfun = 'reload_frame();';
    api.execScript({
        name: api.winName,
        script: jsfun
    });


}


window.QlyApi = {} ; 



window.QlyApi.getVersion = function(){
    if(api.systemType=='ios'){
        return IOS_VERSION ; 
    }else{
        return ANDROID_VERSION ; 
    }

}

window.QlyApi.getVersionCode = function(){
    if(api.systemType=='ios'){
        return IOS_VERSION_CODE ; 
    }else{
        return ANDROID_VERSION_CODE ; 
    }
}

window.QlyApi.getTalkingdata = function(){
    if(TALKINGDATA==null){
        TALKINGDATA = api.require('talkingData');
        if(TALKINGDATA){
            TALKINGDATA.setGlobalKV({
                key:'version_code',
                value:QlyApi.getVersionCode()
            });
        }
    }
    return TALKINGDATA ; 
}




/**
 * params 
 * url:
 * paramData:
 * call_fun
 */
window.QlyApi.load = function(params,tipStr){
    QlyApi.checkConnectionType(function(){
        QlyApi.show_loading(tipStr);
        var url = params.url ; 
        var paramData = params.paramData ||{} ; 
                paramData.token = $api.getStorage('token') ;
                paramData.v = QlyApi.getVersion();
                api.ajax({
                    url: SERVICE_URL+ url,
                    method: 'post',
                    dataType:'json',
                    data: {
                        values:paramData
                    }
                },function(res, err){
                    QlyApi.close_loading();
                    if(res){
                        if(res['new_token'] && res['new_token_expiry']){
                            $api.setStorage('token',res['new_token']) ;
                            $api.setStorage('token_expiry',res['new_token_expiry']) ;                  
                        }
                        params.call_fun(res);
                    }else{
                        api.cancelAjax();
                        $api.html($api.byId(ReloadPageParam.div_id),reload_html);
                    }
                });
    });
}


/**
 *params 
 * url:
 * paramData:
 * call_fun
 * sec_fun
 */
window.QlyApi.load_sec = function(params,tipStr){
    QlyApi.checkConnectionType(function(){
        QlyApi.show_loading(tipStr);
        var url = params.url ; 
        var paramData = params.paramData ||{} ; 
        paramData.token = $api.getStorage('token') ;
        paramData.v = QlyApi.getVersion();
        api.ajax({
            url: SERVICE_URL+ url,
            method: 'post',
            dataType:'json',
            data: {
                values:paramData
            }
        },function(res, err){
            QlyApi.close_loading();
            if(res){
                if(!!res.errno&&res.errno==-999){
                    if(params.sec_fun && typeof(params.sec_fun) == 'function'){
                        params.sec_fun();
                    }
                    var pageParam = {'last_winName':api.winName, 'last_frameName':api.frameName,'is_refresh_frame':true,'refresh_func':'refresh_frame()'}; 
                    if(api.pageParam){
                        for(var i in api.pageParam){
                            pageParam[i] = api.pageParam;
                        }
                    }

                    //跳转至登陆页面
                    QlyApi.openWindowAndFrame({
                            winParams:{
                                    name: 'login_window',
                                    slidBackEnabled:false,
                                    url: 'widget://html/login_window.html',
                                    animation: {
                                        type: 'push',
                                        subType: 'from_bottom',
                                        duration: 300
                                    }
                            },
                            frameParams:{
                                name:'login_frame' , 
                                url:'widget://html/login.html'
                            },
                            'pageParam':pageParam,
                            window_title:"登录"
                        }) ;
                }else{
                    if(res['new_token'] && res['new_token_expiry']){
                        $api.setStorage('token',res['new_token']) ;
                        $api.setStorage('token_expiry',res['new_token_expiry']) ;
                    }
                    params.call_fun(res); 
                }
            }else{
                api.cancelAjax();
                
               $api.html($api.byId(ReloadPageParam.div_id),reload_html);
            }
        });

    });

}



/***
并发多个ajax 请求 ，当全部请求完成后 调用回调函数
[   
    {
        url:'',
        paramData:{},
        var_name:'abc'
    },
    {
        url:'',
        paramData:{},
        var_name:'abc'
    }
]
*/
// window.QlyApi.multiLoad = function (paramsList,multicall_fun){
//     var multiRet = {} ; 
//     QlyApi.recLoad(paramsList,multiRet,multicall_fun) ;
// }


window.QlyApi.multiLoad = function(paramsList,multicall_fun){
    QlyApi.checkConnectionType(function(){
        var multiRet = {} ; 
        var max_length = paramsList.length ; 
        var index = 0 ; 
        for(var i = 0 ; i < paramsList.length ; i ++){
            var param = paramsList[i]; 
            (function(p){
                p.paramData.token = $api.getStorage('token') ; 
                p.paramData.v = QlyApi.getVersion();
                api.ajax({
                    url: SERVICE_URL+p.url,
                    method: 'post',
                    dataType:'json',
                    data: {
                        values:p.paramData
                    }
                 },
                function(ret, err){
                        if (ret) {    //有数据
                            if(ret['new_token'] && ret['new_token_expiry']){
                                $api.setStorage('token',ret['new_token']) ;
                                $api.setStorage('token_expiry',ret['new_token_expiry']) ;
                            }
                            multiRet[p.var_name] = ret ; 
                        } else {   //错误 
                            api.cancelAjax();
                            $api.html($api.byId(ReloadPageParam.div_id),reload_html);
                            return ;
                        }
                        index ++ ;
                        if(index == max_length){
                            multicall_fun(multiRet) ;
                        }
                });
            })(param);
        }
    });
}



window.QlyApi.multiLoad_sec = function (paramsList,multicall_fun){
    QlyApi.checkConnectionType(function(){
       if(!!!$api.getStorage('token')){  //未登陆
            //跳转至登陆页面
            var pageParam = {'last_winName':api.winName, 'last_frameName':api.frameName,'is_refresh_frame':true,'refresh_func':'refresh_frame()'}; 
                if(api.pageParam){
                    for(var i in api.pageParam){
                        pageParam[i] = api.pageParam;
                    }
                }

                //跳转至登陆页面
                QlyApi.openWindowAndFrame({
                        winParams:{
                                name: 'login_window',
                                slidBackEnabled:false,
                                url: 'widget://html/login_window.html',
                                animation: {
                                    type: 'push',
                                    subType: 'from_bottom',
                                    duration: 300
                                }
                        },
                        frameParams:{
                            name:'login_frame' , 
                            url:'widget://html/login.html'
                        },
                        'pageParam':pageParam,
                        window_title:"登录"
                    }) ;
       }else{ //已经登陆
            QlyApi.multiLoad(paramsList,multicall_fun);
       } 
   });
}



/***
递归加载
*/
QlyApi.recLoad = function(paramsList,multiRet,multicall_fun){
    if(paramsList.length==0){
        multicall_fun(multiRet);
    }else{
        var param = paramsList.pop(); 
        param.paramData.token = $api.getStorage('token') ;
        param.paramData.v = QlyApi.getVersion();
        QlyApi.load({
            url:param.url,
            paramData:param.paramData,
            call_fun:function(ret){
              multiRet[param.var_name] = ret ; 
              QlyApi.recLoad(paramsList,multiRet,multicall_fun);
            }
         });
    } 
}

window.QlyApi.getFromPageStr = function(){
    if(api.pageParam.from_page){
        var crWinTitle = api.pageParam.remote_url == "resource/page/vender/vender_detail.html"?"乐园详情":api.pageParam.window_title  ;
        return api.pageParam.from_page + "_" + crWinTitle  ; 
    }else{
        return api.pageParam.window_title ; 
    }
}
//此函数 只用于 统计 最终能到购买页面的 漏斗数据
window.QlyApi.talkingDataOnEvent = function(eventId,parameters){
    if(QlyApi.getTalkingdata()){
        QlyApi.getTalkingdata().onEvent({
            eventId:"buy_"+eventId+"-"+QlyApi.getFromPageStr(),
            eventLabel:QlyApi.getFromPageStr(),
            parameters:parameters||null
        });
    }
}

/****
 *{
        
    winParams:{},  //openWindow 所需参数
    pageParam:{},   //页面传递参数
    frameParams:{}   // oepnFrame 所需参数
    window_title:'hehehe'
 }
 */
window.QlyApi.openWindowAndFrame = function(params){    
    var crWinTitle = api.pageParam.remote_url == "resource/page/vender/vender_detail.html"?"乐园详情":api.pageParam.window_title  ;

    var from_page =  crWinTitle || ""  ; 
    if(api.pageParam.from_page){
        from_page = api.pageParam.from_page+"_"+from_page ; 
    }

    params.frame = {} ; 
    var winParams = {} ; 
    for(var i in params.winParams){
        winParams[i] = params.winParams[i] ; 
    }
    winParams.pageParam =  params.pageParam  || {}; 
    winParams.pageParam.frameParams = {} ; 
    for(var i in params.frameParams){
        winParams.pageParam.frameParams[i] = params.frameParams[i] ; 
    }
    winParams.pageParam.window_title = params.window_title ||"" ;
    winParams.pageParam.from_page = from_page ; 
    api.openWin(winParams);
}

/****
 *{
        
    winParams:{},  //openWindow 所需参数
    pageParam:{},   //页面传递参数
    frameParams:{}   // oepnFrame 所需参数
    window_title:'hehehe',
    remote_url:{}   //远程url 
 }
 */
window.QlyApi.openWindowAndFrameComm = function(params){
    var crWinTitle = api.pageParam.remote_url == "resource/page/vender/vender_detail.html"?"乐园详情":api.pageParam.window_title  ;
    var from_page =  crWinTitle || ""  ; 
    if(api.pageParam.from_page){
        from_page = api.pageParam.from_page+"_"+from_page ; 
    }

    params.frame = {} ; 
    var winParams = {} ; 
    for(var i in params.winParams){
        winParams[i] = params.winParams[i] ; 
    }
    winParams.pageParam =  params.pageParam  || {}; 
    winParams.pageParam.frameParams = {} ; 
    for(var i in params.frameParams){
        winParams.pageParam.frameParams[i] = params.frameParams[i] ; 
    }
    winParams.pageParam.frameParams['url'] = 'widget://html/comm_frame.html';
    winParams.pageParam.window_title = params.window_title ||"" ;
    winParams.pageParam.from_page = from_page;
    winParams.pageParam.remote_url = params.remote_url; 
    api.openWin(winParams);
}



window.QlyApi.openWindowAndFrameNavbar = function(params){
    var crWinTitle = api.pageParam.remote_url == "resource/page/vender/vender_detail.html"?"乐园详情":api.pageParam.window_title  ;
    
    var from_page =  crWinTitle || ""  ; 
    if(api.pageParam.from_page){
        from_page = api.pageParam.from_page+"_"+from_page ; 
    }

    var winParams = params.winParams ; 
    winParams.url =  winParams.url || "widget://html/navbar_window.html"; 
    winParams.pageParam = params.pageParam || {}; 
    winParams.pageParam.navbarParams = params.navbarParams ; 
    winParams.pageParam.window_title = params.window_title || "" ;
    winParams.pageParam.from_page = from_page ;
    api.openWin(winParams);
}

window.close_cur_window = function(){
    if(QlyApi.getTalkingdata()){
        QlyApi.getTalkingdata().onPageEnd({pageName:api.pageParam.window_title});
    } 
    api.closeWin({
        animation: {
            type: 'push',
            subType: 'from_left',
            duration: 300
        }
    });
}

window.QlyApi.show_loading = function(title,text){
    title = !title ? '努力加载中…':title  ;
    text = !text ? '请稍候…':text ;  
    api.showProgress({
                style: 'default',
                animationType: 'fade',
                'title': title,
                'text': text,
                modal: true
    });
}
window.QlyApi.close_loading = function(){
    api.hideProgress();
}

window.QlyApi.closeWindow = function(params){
    if(QlyApi.getTalkingdata()){
        QlyApi.getTalkingdata().onPageEnd({pageName:api.pageParam.window_title});
    } 
    api.closeWin(params);
}

window.QlyApi.venderBanner = function(imgPaths,bkImg){
        var paths = [] ; 
        if(imgPaths&&imgPaths.length>0){
            
            for(var i = 0 ; i <imgPaths.length ; i ++ ){
                 if(imgPaths[i]&&imgPaths[i]!=null){
                    paths.push(imgPaths[i]) ; 
                 } 
            }
        }else{
            if(bkImg){
                paths.push(bkImg);
            }
        }

         var UIScrollPicture = api.require('UIScrollPicture');
         UIScrollPicture.open({
             rect: {
                 x: 0,
                 y: 0,
                 w: api.winWidth,
                 h: 180
             },
             data: {
                 paths: paths
                    },
             styles: {
                 caption: {
                     height: 35,
                     color: '#E0FFFF',
                     size: 13,
                     bgColor: '#696969',
                     position: 'bottom'
                 },
                 indicator: {
                     align: 'center',
                     color: '#FFFFFF',
                     activeColor: '#DA70D6'
                 }
             },
             placeholderImg: 'widget://res/slide1.jpg',
             contentMode: 'scaleToFill',
             interval: 3,
             loop: true,
             fixedOn: api.frameName,
             fixed: false
         },function( ret, err ){
         });
    
}

window.QlyApi.timerFormatDay = function(timerStr){

    if(timerStr&&timerStr.length == 14){
        var str = timerStr.substring(0,4) ; 
        str+= "年" ; 
        str+= timerStr.substring(4,6) ; 
        str+= "月" ;
        str+= timerStr.substring(6,8) ; 
        str+= "日" ; 
        return str ; 
    }else{
        return timerStr;  
    }
   
}
window.QlyApi.timerFormat = function(timerStr){

    if(timerStr&&timerStr.length == 14){
        var str = timerStr.substring(0,4) ; 
        str+= "年" ; 
        str+= timerStr.substring(4,6) ; 
        str+= "月" ;
        str+= timerStr.substring(6,8) ; 
        str+= "日 " ; 
        str+= timerStr.substring(8,10) ;
        str+= ":";
        str+= timerStr.substring(10,12) ;
        str+= ":";
        str+= timerStr.substring(12,14) ; 
        return str ; 
    }else{
         return timerStr; 
    }
}


window.QlyApi.checkBindMobileToWindow = function(){
    if(!($api.getStorage('is_bind_mobile')==1)){
        //跳转至登陆页面
        QlyApi.openWindowAndFrameComm({
                winParams:{
                        name: 'bind_mobile_window',
                        slidBackEnabled:false,
                        url: 'widget://html/window.html',
                        animation: {
                            type: 'push',
                            subType: 'from_bottom',
                            duration: 300
                        }
                },
                frameParams:{
                    name:'bind_mobile_frame' 
                },
                'pageParam':{},
                window_title:"绑定手机号",
                remote_url:'resource/page/bindmobile/bind_mobile.html'
            }) ;
        return false ;
    }else{
        return true  ;
    }
}

window.QlyApi.checkLoginToWindow = function(){

    var timestamp=new Date().getTime();
    if(!!!$api.getStorage('token')||!$api.getStorage('token_expiry') || $api.getStorage('token_expiry') < timestamp/1000){
        // 跳转至登陆页面
        QlyApi.openWindowAndFrame({
                winParams:{
                        name: 'login_window',
                        slidBackEnabled:false,
                        url: 'widget://html/window.html',
                        animation: {
                            type: 'push',
                            subType: 'from_bottom',
                            duration: 300
                        }
                },
                frameParams:{
                    name:'login_frame' , 
                    url:'widget://html/login.html'
                },
                'pageParam':{},
                window_title:"登录"
            }) ;
        return false ;
    }else{
        return true  ;
    }


}

//提示网络差
window.QlyApi.alertPoorNetwork= function(){
    //此处需实现 提示 网络 较差 样式
    $api.prepend($api.byId('main_div'),"<div id='id_poor_network' class='list_poorNetwork'><span></span>当前网络差，请检查您的网络</div>");
    setTimeout('Close_Poor_network()',3000) ; 
}

function Close_Poor_network(){
    $api.remove($api.byId('id_poor_network'));
}

window.QlyApi.checkConnectionType = function(callback_fun){

    
    $api.setStorage('connectionType',api.connectionType);
    
    if('offline'==$api.getStorage('connectionType')){
        //显示重新加载 按钮 
        
        $api.html($api.byId(ReloadPageParam.div_id),reload_html);
        return ; 
    }else if('2g'==$api.getStorage('connectionType')){
        QlyApi.alertPoorNetwork();
    }
    if(callback_fun && typeof callback_fun == 'function'){
        callback_fun();
    }
}


window.QlyApi.checkShowNewVersion = function(callback_fun){
    var cur_v  =  QlyApi.getVersion();
    // TODO 
    //ajax 请求 最新版本信息 ， 
    // 调用 更新方法
   api.ajax({
        url: SERVICE_URL+'version/check',
        method: 'post',
        data: {
            values: { 
                v:QlyApi.getVersion()
            }
        }
    },function(ret, err){
        if (ret&&!!!ret.errno && ret['version_sn']) { //有更新
            var last_v =  $api.getStorage("last_alert_version");
            if(last_v == null ||last_v != ret.version_sn){
                QlyApi.showUpdateMsg(ret) ;
                if(!ret.force){  //如果是强制更新的话 ，每次都会弹更新提示
                    $api.setStorage("last_alert_version",ret.version_sn) ;
                    if(callback_fun && typeof callback_fun == 'function'){
                        callback_fun();
                    } 
                }
            }else{
                if(callback_fun && typeof callback_fun == 'function'){
                    callback_fun();
                } 
            }
            
        }else{
           if(!!!err){
                if(callback_fun && typeof callback_fun == 'function'){
                        callback_fun();
                } 
           }
        }

    });  
}

/*
    {
        login:function(){},
        notlogin:function(){}
    }

*/
//检查是否处于登录状态 ，否则跳转到 登录窗口 
window.QlyApi.checkLogin = function (params){
    var timestamp=new Date().getTime();
    //判断cookie 是否 登陆
    if(!!$api.getStorage('token') && !!$api.getStorage('token_expiry')  &&  $api.getStorage('token_expiry') > timestamp/1000 ){  //登陆成功
        if(params.login!=undefined && typeof(params.login) == 'function'){
            params.login();
        }
    }else{ //未登陆
        if(params.notlogin!=undefined && typeof(params.notlogin) =='function'){
            params.notlogin();
        }
    }
    //发送ajax 请求 判断 cookie 是否 正确
}












window.QlyApi.showUpdateMsg = function(params){  
    if(params.force){
        api.confirm({
            title: '更新提示',
            msg: '有新版本了！\n 最新版本：'+params.version_code+' \n \n 更新描述：\n '+params.version_des+'\n \n 更新时间：'+params.time,
            buttons: ['关闭', '更新']
        }, function(ret, err){
            if( ret ){
                 if(ret.buttonIndex == 2){
                    updataBtn(params.source);
                 }else{
                    api.closeWidget({silent:true}); //退出应用
                 }
            }else{
            }
        });
    }else{
        api.confirm({
            title: '更新提示',
            msg: '有新版本了！\n 最新版本：'+params.version_code+' \n \n 更新描述：\n '+params.version_des+'\n \n 更新时间：'+params.time,
            buttons: ['继续使用', '更新']
        }, function(ret, err){
            if( ret ){
                 if(ret.buttonIndex == 2){
                    updataBtn(params.source);
                 }else{
                    api.alert({
                        title: '提示',
                        msg: '取消更新可能会影响部分功能的正常使用',
                    });
                 }
            }else{
            }
        });
    }
}
function updataBtn(source){ //判断手机类型
    if(api.systemType=='ios'){
        installIosApp(source);
    }else{
        installAndroidApp(source);
    }
}
/* 安装 iOS 应用. */
function installIosApp(source){
    api.installApp({
        appUri: source
    });
}
/*------------------*/
/* 安装 Android 应用. */
function installAndroidApp(source){// 需要先下载到本地.
    api.download({
        url: source,
        report: true
    }, function(ret, err){
        if(ret && 0 == ret.state){/* 下载进度 */
            api.showProgress({
                style: 'default',
                animationType: 'fade',
                title: '正在下载',
                text: ret.percent+'%',
            });
        }
        if (ret && 1 == ret.state) {/* 下载完成 */
            var savePath = ret.savePath;
            api.installApp({
                appUri: savePath
            });
        }
    });
}
/*------------------*/




